<template>
  <div>
    <!-- 旧件出库新增 - 车厂 - 详情页面 -->
    <BreakSpace label="出库信息" :containerStyle="{ marginBottom: '10px' }" />
    <FormPanel ref="formPanel1" :list="formList" :cols="3" :formType="'add'" labelWidth="90" :isSubmitBtn="false" @formChange="formChangeHandle" />
    <div style="padding-top: 3rem;"></div>

    <BreakSpace label="旧件列表" :containerStyle="{ marginBottom: '10px' }" />
    <FilterTable
      ref="table"
      :columns="columns"
      :params="fetchParams"
      :dataSource="dataList"
      :datakey="'items'"
      :onColumnsChange="columns => (this.columns = columns)"
      :onRowSelectChange="selectChange"
      selectionType="single"
      height="auto"
      :isPagination=false
      :isSelectColumn=false
    >
    </FilterTable>
    <BaseDialog :visible.sync="jiujianFlag" :title="'旧件选择列表'" destroyOnClose :containerStyle="{height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px'}">
      <selectjiujian @close="jiujianclose" @save="saveMaintainItemSelect"></selectjiujian>
    </BaseDialog>
    <div style="margin-bottom: 1rem;"></div>
    <div style="padding-top: 3rem;"></div>
    <div
      :style="{
        position: 'absolute',
        left: 0,
        bottom: 0,
        right: 0,
        zIndex: 9,
        borderTop: '1px solid #e9e9e9',
        padding: '10px 20px',
        background: '#fff',
        textAlign: 'right'
      }"
    >
    <!--   <multiuse-button type="primary" icon="el-icon-printer" :disabled="this.rowData.outStatus != 55691001" @click="print()">打 印</multiuse-button> -->
      <multiuse-button @click="closeDialog">返 回</multiuse-button>
    </div>
    <BasePrint ref="templateReturnList" :data="printList" template="templateReturnListOEM" direction="horizontal"/>
  </div>
</template>
<script>
// import res from '@/mock/tableData';
//手机号校验
import { phone } from '@/utils/validate';
//日期、时间控件默认值设置
import moment from 'moment';
import selectjiujian from './selectjiujian.vue';
//公共方法
import { getPartType, getSupplierList } from '@/api/dictionary/index.js';
import { dictionary } from '@/utils/dictMixin';
import { selectById} from '@/api/usedPartsReturnManage/usedPartsReturn_OEM/usedPartsOutOfStock';

export default {
  props: ['rowData'],
  mixins: [dictionary],
  components: {
    selectjiujian
  },
  data() {
    return {
      editData: [],
      dataList: [],
      visible: false,
      visibleDrawer: false,
      collapse: false,
      jiujianFlag: false,
      columns: this.creatHeader(),
      fetchParams: {}, //ipa 接口
      selectedRows: [], //选中服务站
      formList: this.createFormList(),
      saveData: null,
      printList: {
        rows: []
      }
    };
  },
  created() {
    // this.chuqi();
    //this.chuqi2();
    this.init(this.rowData.outId);
  },
  methods: {
    //供应商下拉框
    // async chuqi() {
    //   console.log("===== 获取下拉框数据 ====== ")
    //   const res = await getSupplierList();
    //   console.log("==========",res)
    //   if (res.resultCode == 200) {
    //     this.formList.find(x => x.fieldName == 'supCode').initialValue = '';
    //     this.formList.find(x => x.fieldName == 'supCode').itemList = res.data.map(y => ({ text: y.supName, value: y.supCode }));
    //   }
    // },
    /* async print() {
      console.log("打印")
      let newVar = await printById({id: this.rowData.outId});
      this.printList = newVar.data;
      this.$nextTick(() => {
        this.$refs.templateReturnList.EXCUTE_PRINT();
      });
    }, */
    //出库类型下拉框
    async chuqi2() {
      console.log("===== 获取下拉框数据 ====== ")
      const res = await getPartType({ type: 5523 });
      console.log("==========",res)
      if (res.resultCode == 200) {
        this.formList.find(x => x.fieldName == 'outType').initialValue = '';
        this.formList.find(x => x.fieldName == 'outType').itemList = res.data.map(y => ({ text: y.codeCnDesc, value: y.codeId }));
      }
    },
    async init(val) {
      let newVar = await selectById({id: val});
      this.editData = newVar.data;
      console.log("=== 通过ID查询结果返回 ==== ",newVar," ======");
      this.formList.forEach(x => {
        console.log(newVar);
        x.initialValue = newVar.data[x.fieldName];
      });
      this.$refs.table.$refs.pageTable.EXECUTE_INSERT(newVar.data.dtlList);
    },
    formChangeHandle(val) {
      console.log(val);
      this.saveData = val;
    },
    //搜索获取数据
    changeHandle(val) {
      this.fetchParams = val;
      console.log(val);
    },
    //选中
    selectChange(rows) {
      this.selectedRows = rows;
      console.log(this.selectedRows);
    },
    //取消操作
    closeDialog() {
      this.$emit('close', { visible: false, data: this.selectedRows, type: 'close' });
    }, //服务站选择页面
    SelectDelear() {
      this.selectDelearFlag = true;
    }, //关闭
    Delearclose() {
      this.selectDelearFlag = false;
    },
    //删除
    deleteHandle(row) {
      this.$refs.table.$refs.pageTable.EXECUTE_DELETE([row]);
    },
    //保存
    async saveDialog() {
      this.$refs.formPanel1.SUBMIT_FORM();

      if (this.saveData !== null) {
        if (this.dataList.find((x) => Number(x.outCount) > 0)) {

          //单据状态 旧件回运草稿字典码
         // this.saveData.outStatus = 55691002;

          let save = {};
          save =  this.saveData;

          for (let a in this.editData){
            if(this.dataList[a]){
              this.editData[a] = this.dataList[a];
            }
          }

          save.dtlList = this.editData;

          console.log("dlt=======",save.dtlList);

          let res = await newSave(save);
          console.log(res);
          if (res.resultCode === 200) {
            this.$emit('save');
            return this.$notify.success({ title: '提示信息', message: '保存成功' });
          } else {
            this.$notify.error({ title: '提示信息', message: res.errMsg || '保存失败!' });
            this.closeDialog();
          }

        }else {
          return this.$notify.warning({ title: '提示信息', message: '未填写回运数量' });
        }
      } else {
        return this.$notify.warning({ title: '提示信息', message: '有未校验通过的信息' });
      }
    },
    //出库
    async saveDialog2() {
      this.$refs.formPanel1.SUBMIT_FORM();

      if (this.saveData !== null) {
        if (this.dataList.find((x) => Number(x.outCount) > 0)) {

          //单据状态 旧件回运出库字典码
         // this.saveData.outStatus = 55691001;

          let save = {};
          save =  this.saveData;

          for (let a in this.editData){
            if(this.dataList[a]){
              this.editData[a] = this.dataList[a];
            }
          }

          save.dtlList = this.editData;

          console.log("dlt=======",save.dtlList);

          let res = await newSave(save);
          console.log(res);
          if (res.resultCode === 200) {
            this.$emit('save');
            return this.$notify.success({ title: '提示信息', message: '保存成功' });
          } else {
            this.$notify.error({ title: '提示信息', message: res.errMsg || '保存失败!' });
            this.closeDialog();
          }

        }else {
          return this.$notify.warning({ title: '提示信息', message: '未填写回运数量' });
        }
      } else {
        return this.$notify.warning({ title: '提示信息', message: '有未校验通过的信息' });
      }
    },
    //子页面带回数据
    saveMaintainItemSelect(val) {
      console.log(val);
      this.editData = val;
      this.jiujianFlag = false;
      let list = Object.assign([], val)
      let pageList = this.$refs.table.$refs.pageTable.list;
      val.map(x => {
        if(pageList.find(f => f.claimId != x.claimId)) {
          list.push(x);
        }
      });
      console.log("=====",list)
      this.$refs.table.$refs.pageTable.EXECUTE_DELETE(this.$refs.table.$refs.pageTable.list);
      this.$refs.table.$refs.pageTable.EXECUTE_INSERT(list);
      this.fetchParams = { ...this.fetchParams };
    },
    chooseOrderNo() {
      this.visible = true;
    },
    add() {
      this.jiujianFlag = true;
    },
    jiujianclose() {
      this.jiujianFlag = false;
    },
    createFormList() {
      return [
        {
          type: 'INPUT',
          label: '出库单号',
          fieldName: 'outNo',
          readonly: true,// 只读
          disabled: true // 置灰
        },
        {
          type: 'SELECT',
          label: '出库类型',
          fieldName: 'outType',
          placeholder: '请选择出库类型...',
          itemList: this.createDictList('5523'),
          // rules: [{ required: true, message: '请选择出库类型', trigger: 'change' }],
          readonly: true, // 只读
          disabled: true // 置灰

        },
        {
          type: 'INPUT',
          label: '供应商名称',
          fieldName: 'supName',
          // rules: [{ required: true, message: '请选择出库类型', trigger: 'change' }],
          readonly: true, // 只读
          disabled: true // 置灰
        },
        {
          type: 'DATE',
          label: '出库日期',
          fieldName: 'updatedAt',
          placeholder: '选择日期...',
          readonly: true, // 只读
          disabled: true // 置灰
          // rules: [{ required: true, message: '请选择日期', trigger: 'change' }]
        },
       /*  {
          type: 'INPUT',
          label: '领件人',
          placeholder: '请输入领件人...',
          fieldName: 'outTo',
          readonly: true, // 只读
          disabled: true // 置灰
        },
        {
          type: 'INPUT',
          label: '联系电话',
          fieldName: 'outPhone',
          placeholder: '请输入联系电话...',
          rules: [{ validator: phone, trigger: 'blur' }],
          readonly: true, // 只读
          disabled: true // 置灰
        }, */
        {
          type: 'TEXT_AREA',
          label: '备注',
          fieldName: 'outRemarks',
          placeholder: '请输入备注...',
          selfCols: 2,// 元素占据几行
          rows:2,
          readonly: true, // 只读
          disabled: true // 置灰
        }
      ];
    },

    //旧件列表
    creatHeader() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 80,
          sorter: true,
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
       /*  {
          title: '操作',
          width: 150,
          dataIndex: 'column-action',
          //disabled:true,
          render: (props, h) => {
            return (
              <div style="text-align:center">
                <multiuse-button size="mini" type="text" onClick={() => this.deleteHandle(props.row)} disabled={true} >
                  删除
                </multiuse-button>
              </div>
            );
          }
        }, */
       /*  {title: '索赔单号', dataIndex: 'cmsClaimNo', sorter: true}, */
        {title: '旧件代码', dataIndex: 'partCode', sorter: true},
        {title: '旧件名称', dataIndex: 'partName', sorter: true},
        {title: '库存类型', dataIndex: 'outStatus ', sorter: true,  dictItems: [{ text: '合格库', value: 1 },{ text: '不合格库', value: 0 }],},
        {title: '库存数量', dataIndex: 'stockCount', sorter: true},
        {title: '出库数量', dataIndex: 'outCount', sorter: true},

      ];
    }
  }
};
</script>
<style lang="less" scoped></style>
